package com.codeanalysissys.backend.enums;

import com.codeanalysissys.backend.entity.TypeAnalysisEnum;
import org.springframework.core.convert.converter.Converter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class TypeToEnumConverter <T extends TypeAnalysisEnum> implements Converter<String, T> {
//    private final Map<String, T> typeEnumMap = Maps.newHashMap();
//    private final Map<String, T> graphEnumMap = Maps.newHashMap();
    private final Map<String, T> typeEnumMap = new HashMap<>();
    private final Map<String, T> graphEnumMap = new HashMap<>();

    public TypeToEnumConverter(Class<T> enumType) {
        Arrays.stream(enumType.getEnumConstants())
                .forEach(x -> {
                    typeEnumMap.put(x.getType().toString(), x);
                    graphEnumMap.put(x.getGraph(), x);
                });
    }

    @Override
    public T convert(String source) {
        return Optional.of(source)
                .map(graphEnumMap::get)
                .orElseGet(() -> Optional.of(source)
                        .map(typeEnumMap::get)
                        .orElseThrow(RuntimeException::new));
    }

    @Override
    public <U> Converter<String, U> andThen(Converter<? super T, ? extends U> after) {
        return Converter.super.andThen(after);
    }
}
